package com.gfm.story.interceptor;

import com.gfm.story.constants.CommonConstants;
import com.gfm.story.entity.user.User;
import com.google.common.base.Joiner;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @BelongsProject: house-parent
 * @BelongsPackage: com.mooc.house.web.interceptor
 * @Author: Administrator
 * @CreateTime: 2019-04-24 15:05
 * @Description: 拦截器1：页面访问权限鉴权
 *                      设置登录后才能访问的页面
 *                      拦截除静态资源以外的任何资源，并且从session中取user放到ThreadLocal中
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {

    /**
     * Controller执行之前调用拦截执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        //获取所有请求参数
        Map<String, String[]> map = request.getParameterMap();
        map.forEach((k,v) -> {
            if (k.equals("errorMsg") || k.equals("successMsg") || k.equals("target")) {//重定向时附加的参数
                request.setAttribute(k, Joiner.on(",").join(v));//将几个字符串，或者字符串数组、列表之类的东西，拼接成一个以指定符号分隔各个元素的字符串，比如把 [1, 2, 3] 拼接成 "1 2 3"。
                System.out.println("================================================:"+k);
            }
        });
        String reqUri =	request.getRequestURI();//获取请求路径
        //判断是不是静态资源请求或者是一个Spring自己error的请求
        if (reqUri.startsWith("/static") || reqUri.startsWith("/error") ) {
            return true;
        }
        //true如果没有session则创建一个
        HttpSession session = request.getSession(true);
        //拿到Session中保存的User信息
        User user =  (User)session.getAttribute(CommonConstants.USER_ATTRIBUTE);
        if (user != null) {
            UserContext.setUser(user);//存储UserSession到线程
        }
        return true;
    }

    /**
     * Controller方法执行完之后拦截
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

    }

    /**
     * 在页面渲染完成之后执行
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        //页面渲染完成后清空线程中存储的Session信息
        UserContext.remove();
    }
}
